﻿using System;
using CzfSDK;
using System.Data;
using System.Collections;
using System.Collections.Generic;

namespace Server
{
	public class User
	{
		#region static
		static object _list_lock = new object();
		public static List<User> users = new List<User> ();
		public static User Get(int id)
		{
//			lock (_list_lock) {
				for (int i = 0; i < users.Count; i++) {
					var p = users [i];
					if (p.id == id) {
						return p;
					}
				}
				return null;
//			}
		}

		public static User Get(CzfNetClient client)
		{
			if (client == null)
				throw new Exception ("client cant be null!");
//			lock (_list_lock) {
				for (int i = 0; i < users.Count; i++) {
					var p = users [i];
					if (p.client == client) {
						p.last = DateTime.Now;
						return p;
					}
				}
				return null;
//			}
		}

		public static void Add(User user)
		{
			lock (_list_lock) {
				users.Add (user);
			}
		}

		public static void Remove(User user)
		{
			lock (_list_lock) {
				users.Remove (user);
			}
		}
		#endregion

		public int id;
		public string name;
		public CzfNetClient client;
		public Hashtable data;
		public Room room;
		public DateTime last;

		public User (Hashtable ht, CzfNetClient client)
		{
			if (ht != null) {
				data = ht;
//				data.Remove ("password");
				id = data.GetVal<int> ("id");
				name = data.GetVal<string> ("name");
				this.client = client;
				User.Add (this);
			}
		}

		public void Logout()
		{
			CzfLog.Info ("{0} Logout".CzfFormat(name));
			UserManager.UserLogout (id);
			if (room != null) {
				room.UserOut (this);
			}
			if (client != null)
				client.Close ();
			Destroy ();
		}

		public void Destroy()
		{
			User.Remove (this);
		}
	}
}

